//
//  OAuthViewController.swift
//  glzbowei
//
//  Created by 高伦展 on 2017/12/4.
//  Copyright © 2017年 glz. All rights reserved.
//

import UIKit
import SVProgressHUD

class OAuthViewController: UIViewController {

    private lazy var webView = UIWebView()
    
    @objc private func close()
    {
        SVProgressHUD.dismiss()
        dismiss(animated: true) { }
    }
    
    ///自动填充用户名和密码 - web 注入（以代码的方式向web页面添加内容）
    @objc private func autoFill()
    {
        let js = "document.getElementById('userId').value = 'glz090923@163.com';" +
        "document.getElementById('passwd').value = 'glz19900825';"
        
        //让 webView 执行 js
        webView.stringByEvaluatingJavaScript(from: js)
    }
    
    override func loadView() {
        view = webView
        
        title = "登录新浪微博"
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: UIBarButtonItemStyle.plain, target: self, action: #selector(OAuthViewController.close))
        
          navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", style: UIBarButtonItemStyle.plain, target: self, action: #selector(OAuthViewController.autoFill))
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        //在开发中，如果用纯代码开发，视图最好都指定背景颜色，如果为nil，会影响渲染效率
        //view.backgroundColor = UIColor.white
        
        //加载页面
        self.webView.loadRequest(NSURLRequest(url: NetworkTools.sharedTools.oauthURL as URL) as URLRequest)
        
        self.webView.delegate = self;
    }
 
}

/// MARK: - UIWebViewDelegate
extension OAuthViewController : UIWebViewDelegate{
 
    /// 将要加载请求的代理方法
    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        guard let url = request.url, url.host == "zhanxinstudio.info" else{
            return true
        }
        
        guard let query = url.query, query.hasPrefix("code=") else{
            print("取消授权")
            
            return false
        }
        
        let code = query.suffix(from: "code=".endIndex)
        
        print(query)
        print("授权码是: "+code)
        
        UserAccountViewModel.sharedUserAccount.loadAccessToken(code: String(code)) { (isSuccessed) in
            if !isSuccessed{
               SVProgressHUD.showInfo(withStatus: "登录失败")
                
                delay(delta: 0.2, callFunc: {
                    self.close()
                })
                
            }
            else{ 
                SVProgressHUD.dismiss()
                //dismiss 方法不会立即将控制器销毁
                self.dismiss(animated: false, completion: {
                    NotificationCenter.default.post(name: NSNotification.Name(rawValue: WBSwitchRootViewControllerNotification), object: "welcome")
                })
            }
        }
 
        return false;
    }
     
}
